<template>
	<view class="home">
		<view class="home-wheel">
			<view class="winThePrizeRecord" @click="winThePrizeRecord">
				中奖记录
			</view>
			
			<view class="winThePrizeRecord__count">
				抽奖次数：{{ userInfo.prizeCount }}
			</view>
			<almost-lottery :prize-list="prizeList" :ring-count="2" :duration="5" :ringCount="20"
				:canvas-width="canvasData.width" :canvas-height="canvasData.height" :prize-index="prizeIndex"
				@reset-index="prizeIndex = -1" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
				@finish="handleDrawFinish" v-if="prizeList.length" />
			<text class="almost-lottery__tip" v-else>奖品准备中...</text>
		</view>
		<view class="swiper">
			<view class="title">幸运名单</view>
			<swiper display-multiple-items="9" :circular="true" vertical="true" :autoplay="true" :interval="5000" :duration="1000">
				<swiper-item v-for="(item, index) in data" :key="index">
					<text>恭喜 {{ item.nickname.length > 6 ? item.nickname.substring(0, 6) + "..." : item.nickname }} </text>
					<text class="swiper-item-text">获得 {{ item.title.length > 10 ? item.title.substring(0, 10) + "..." : item.title }}</text>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<script>
	import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
	import AlmostLottery from '../../components/almost-lottery/almost-lottery.vue'
	import { getPrizeData, getWinThePrize, getWinThePrizeRecord } from "@/api/public";
	import { clearCacheFile } from '../../almost-utils/almost-utils.js'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				id: '',
				recordId: '',
				// canvas 宽高
				canvasData: {
					width: 240,
					height: 240
				},
				// 奖品数据
				prizeList: [],
				// 中奖下标
				prizeIndex: -1,
				// 是否正在抽奖中
				prizeing: false,
				// 中奖类目名称
				targetName: '',
				// 奖品是否设有库存
				onStock: false,
				// 是否由前端控制概率，默认不开启
				onFrontend: false,
				// 权重随机数的最大值
				weightTotal: 0,
				// 权重数组
				weightArr: [],
				data: [],
				
				hasPrizeCount: '',
				prizeState: ''
			}
		},
		computed: {
			...mapGetters(['userInfo']),
		},
		onLoad() {
			this.$store.dispatch('getUser').then(res => {
				// 模拟请求奖品数据
				this.id = this._route.query.id
				
				this.getPrizeList()
				// this.luckDrawinitData()
			}).catch( err => {
			    this.$yrouter.push("/pages/authorization/index");
			})
			
		},
		onUnload() {
			uni.hideLoading()
		},
		methods: {
			// 获取奖品列表
			async getPrizeList() {
				uni.showLoading({
					title: '奖品准备中...'
				})
				let res = await this.requestPrizeList()
				console.log('获取奖品列表', res)
				if (res.ok) {
					let data = res.data
					if (data.length) {
						// stock 奖品库存
						// weight 中奖概率，数值越大中奖概率越高
						this.prizeList = data
						// 如果开启了前端控制概率
						// 计算出权重的总和并生成权重数组
						if (this.onFrontend) {
							this.prizeList.forEach((item) => this.weightTotal += item.weight)
							this.weightArr = this.prizeList.map((item) => item.weight)
						}
					}
				} else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败'
					})
				}
			},
			// 模拟请求奖品列表接口
			requestPrizeList() {
				return new Promise((resolve, reject) => {
					let requestTimer = setTimeout(() => {
						clearTimeout(requestTimer)
						requestTimer = null
						getPrizeData(this.id).then((res) => {
							this.$set(this, "data", res.data.recordList);
							// this.data = res.data.recordList
							console.log(res.data)
							console.log(res.data.hasPrizeCount)
							this.hasPrizeCount = res.data.hasPrizeCount
							this.prizeState = res.data.prizeState
							if(this.prizeState != 1){
								setTimeout(() => {
									return this.$yrouter.back();
								}, 500);
							}
							resolve({
								ok: true,
								data: res.data.prizeList
							})
						});
					}, 2000)
				})
			},
			// 本次抽奖开始
			handleDrawStart() {
				if(this.hasPrizeCount != 'Y'){
					uni.showModal({
						title: '温馨提示',
						content: '您的抽奖次数为0！',
						success: function(res) {
							if (res.confirm) {
							} else if (res.cancel) {}
						}
					});
					return
				}
				if (this.prizeing) return
				this.prizeing = true
				this.targetName = ''
				let list = [...this.prizeList]
				// 判断是否由前端控制概率
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (this.onFrontend) {
					if (!this.weightTotal) {
						console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 weight 参数似乎配置不正确###')
						return
					}
					console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
					console.log('当前权重总和为 =>', this.weightTotal)
					// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
					let weight = Math.ceil(Math.random() * this.weightTotal)
					console.log('本次权重随机数 =>', weight)
					// 生成大于等于随机权重的数组
					let tempMaxArrs = []
					list.forEach((item) => {
						if (item.weight >= weight) {
							tempMaxArrs.push(item.weight)
						}
					})
					// 如果大于随机权重的数组有值，先对这个数组排序然后取值
					// 反之新建一个临时的包含所有权重的已排序数组，然后取值
					if (tempMaxArrs.length) {
						tempMaxArrs.sort((a, b) => a - b)
						this.prizeIndex = this.weightArr.indexOf(tempMaxArrs[0])
					} else {
						let tempWeightArr = [...this.weightArr]
						tempWeightArr.sort((a, b) => a - b)
						this.prizeIndex = this.weightArr.indexOf(tempWeightArr[tempWeightArr.length - 1])
					}
					console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].name)
					// 如果奖品设有库存
					if (this.onStock) {
						console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].stock)
					}
				} else {
					// 模拟请求获取中奖信息
					let stoTimer = setTimeout(() => {
						clearTimeout(stoTimer)
						stoTimer = null
						console.warn('###当前处于模拟的随机中奖概率，实际场景中，中奖概率应由后端控制###')
						getWinThePrize(this.id).then((res) => {
							console.log(res.data)
							this.hasPrizeCount = res.data.hasPrizeCount
							this.$store.dispatch('getUser').then(res => {}).catch( err => {})
							
							if(res.data.isShow == 0){
								uni.showModal({
									title: '温馨提示',
									content: '该抽奖活动已结束！！！',
									success: function(res) {
										if (res.confirm) {
											setTimeout(() => {
												return this.$yrouter.back();
											}, 500);
										} else if (res.cancel) {}
									}.bind(this)
								});
								return
							}else{
								if(res.data.hasPrizeCount != 'Y'){
									uni.showModal({
										title: '温馨提示',
										content: '您的抽奖次数为0！',
										success: function(res) {
											if (res.confirm) {
											} else if (res.cancel) {}
										}
									});
									return
								}else{
									this.recordId = res.data.detail.id
									this.prizeIndex = res.data.orignalIndex
									this.luckDrawinitData()
								}
							}
							
						});
						// 如果奖品设有库存
						if (this.onStock) {
							console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].stock)
						}
					}, 500)
				}
			},
			// 本次抽奖结束
			handleDrawEnd() {
				this.prizeing = false
				// 旋转结束后，可以执行拿到结果后的逻辑
				let prizeName = this.prizeList[this.prizeIndex].name
				if (this.onStock) {
					let prizeStock = this.prizeList[this.prizeIndex].stockf
					this.targetName = prizeName === '谢谢参与' ? prizeName : prizeStock ? `恭喜您，获得 ${prizeName}` :
						'很抱歉，您来晚了，当前奖品已无库存'
				}
				uni.showModal({
					title: '温馨提示',
					content: this.targetName = prizeName === '谢谢参与' ? prizeName : `恭喜您，获得 ${prizeName}`,
					cancelText: "继续",
					confirmText: "前往兑奖",
					success: function(res) {
						if (res.confirm) {
							this.winThePrizeRecord()
						} else if (res.cancel) {}
					}.bind(this)
				});
				// this.targetName = prizeName === '谢谢参与' ? prizeName : `恭喜您，获得 ${prizeName}`
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)
				uni.showToast({
					title: res.msg,
					duration: 2000,
					mask: true,
					icon: 'none'
				})
			},
			luckDrawinitData(){
				let that = this
				getWinThePrizeRecord(that.recordId).then((res) => {
					that.$set(that, "data", res.data.recordList);
					console.log(res.data)
				});
			},
			winThePrizeRecord(){
				this.$yrouter.push("/pagesB/view/winThePrizeRecord/index");
			}
		}
	}
</script>

<style lang="scss" scoped>
	$wheelBgUrl: 'https://h5.ylsp.vip/file/static/almost-lottery/almost-lottery__bg';

	.home {
		padding-bottom: 50rpx;
		background-color: #ff8841;
		
		.swiper{
			height: 600rpx;
			margin-top: 60rpx;
			
			.title{
				height: 80rpx;
				margin: 0px 70rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #e54724;
				color: #FFFFFF;
				font-weight: bold;
				border-top-left-radius: 12rpx;
				border-top-right-radius: 12rpx;
			}
			
			swiper{
				height: 520rpx;
				margin: 0px 70rpx;
				padding-left: 20rpx;
				padding-right: 20rpx;
				// border: #e54724 solid 1rpx;
				border-bottom-left-radius: 12rpx;
				border-bottom-right-radius: 12rpx;
				background-color: #FFFFFF;
				font-size: 28rpx;
					
				swiper-item{
					height: 70rpx;
					line-height: 70rpx;
					
					.swiper-item-text{
						margin-left: 10rpx;
					}
				}
			}
		}
	}

	.home-title {
		text-align: center;
		margin-bottom: 50px;
	}

	.home-title__text {
		color: #000;
		font-size: 30px;
		font-weight: bold;
	}

	.home-result {
		text-align: center;
		margin-top: 50px;
	}

	.home-result__text {
		color: #000;
		font-size: 20px;
		font-weight: bold;
	}

	.home-wheel {
		position: relative;
		background-image: url('https://h5.ylsp.vip/file/static/images/lottery/top-bg.png');
		text-align: center;
		padding-top: 440rpx;
		background-repeat: no-repeat;
		
		.winThePrizeRecord{
			position: absolute;
			top: 40rpx;
			right: 0;
			background-color: #ff3334;
			height: 70rpx;
			width: 200rpx;
			border-top-left-radius: 70rpx;
			border-bottom-left-radius: 70rpx;
			color: #FFFFFF;
			line-height: 70rpx;
			text-align: center;
			font-size: 30rpx;
			font-weight: bold;
		}
		
		.winThePrizeRecord__count{
			position: absolute;
			top: 40rpx;
			left: 0;
			background-color: #ff3334;
			height: 70rpx;
			width: 230rpx;
			border-top-right-radius: 70rpx;
			border-bottom-right-radius: 70rpx;
			color: #FFFFFF;
			line-height: 70rpx;
			text-align: center;
			font-size: 30rpx;
			font-weight: bold;
		}
	}

	.almost-lottery__tip {
		font-size: 24rpx;
	}

	.home-action {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 40rpx;
		width: 260rpx;
		height: 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto;
	}

	.home-action__text {
		color: #FFFFFF;
		font-size: 24rpx;
	}
</style>
